package sng.data.info
{
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	import mx.collections.ArrayCollection;
	import mx.collections.ArrayList;
	
	/**
	 * 
	 * @author leonliu
	 * 定时器管理
	 * 
	 */	
	public class GlobalTimer
	{
		private static	var timer:Timer;
		public function GlobalTimer()
		{
			
		}
		
		public static var timeFunctionList:ArrayCollection = new ArrayCollection();//事件列表 倒计时时间 function地址 修改为 建筑ID 倒计时时间 function 地址 是否停止
		
		/**
		 *
		 *  设置某id的建筑物在计时列表中的运行状态
		 * @param id
		 * @param blRun
		 * 
		 */		
		public static function setFuncRun(id:uint,blRun:Boolean):void
		{
			for (var i:int = 0; i < timeFunctionList.length; i++) {
				if (timeFunctionList[i].id==id)
				{
					timeFunctionList[i].run=blRun;
					return;
				}
			}
		}
		
		public static function getFuncTime(id:uint):int
		{
			for (var i:int = 0; i < timeFunctionList.length; i++) {
				if (timeFunctionList[i].id==id)
				{
					return	timeFunctionList[i].time;
					
				}
			}
			return 0;
		}
		
		private static var _iCurrentTimerNum:uint;
		
		/**
		 * 
		 * @return 
		 * 当前计时
		 * 
		 */		
		public  static function get iCurrentTimerNum():uint
		{
			return _iCurrentTimerNum;
		}
		
		/**
		 * 
		 * @param hbe
		 * 增加计时器监听事件
		 * 
		 */		
		public static function addHeartBeatEventListener(hbe:Function):void
		{
			timer.addEventListener(TimerEvent.TIMER,hbe);
		}
		
		public static function removeHeartBeatEventListener(hbe:Function):void
		{
			timer.removeEventListener(TimerEvent.TIMER,hbe);
		}
		
		
		public static function Start():void
		{
			timer = new Timer(1000);
			_iCurrentTimerNum=0;
			timer.addEventListener(TimerEvent.TIMER,timerHandler);
			timer.start();
			
			
		}
		
		
		private static function  timerHandler(event:TimerEvent):void
		{
			_iCurrentTimerNum+=1;
			//遍历数组，全部-1秒，如果有等于0的项，则调用数组中的方法执行
			for (var i:int = 0; i < timeFunctionList.length; i++) {
				if(timeFunctionList[i].run)
					timeFunctionList[i].time-=1;
				if (timeFunctionList[i].time==0)
				{
					var f:Function=timeFunctionList[i].func as Function;
					f();					
					//删除此项
					timeFunctionList.removeItemAt(i);//移除后i的值是否要做调整？
				}
			}
		}
		
	}
}